<?php

namespace App\Http\Controllers;

use App\Models\Settlement;
use App\Models\Task;
use App\Models\TaskApplication;
use App\Services\SmsService;
use App\Services\BankService;
use App\Services\TaxService;
use App\Services\KycService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Illuminate\Validation\Rule;

class SettlementController extends Controller
{
    protected $smsService;
    protected $bankService;
    protected $taxService;
    protected $kycService;

    public function __construct(
        SmsService $smsService,
        BankService $bankService,
        TaxService $taxService,
        KycService $kycService
    ) {
        $this->smsService = $smsService;
        $this->bankService = $bankService;
        $this->taxService = $taxService;
        $this->kycService = $kycService;
    }

    /**
     * 获取结算记录列表
     */
    public function index(Request $request)
    {
        $query = Settlement::with(['task', 'taskApplication', 'tenant'])
            ->where('tenant_id', Auth::user()->tenant_id);

        // 搜索过滤
        if ($request->filled('search')) {
            $search = $request->search;
            $query->where(function ($q) use ($search) {
                $q->where('settlement_number', 'like', "%{$search}%")
                  ->orWhereHas('task', function ($taskQuery) use ($search) {
                      $taskQuery->where('title', 'like', "%{$search}%");
                  })
                  ->orWhereHas('taskApplication', function ($appQuery) use ($search) {
                      $appQuery->where('name', 'like', "%{$search}%")
                               ->orWhere('phone', 'like', "%{$search}%");
                  });
            });
        }

        // 状态过滤
        if ($request->filled('status')) {
            $query->where('status', $request->status);
        }

        // 结算类型过滤
        if ($request->filled('type')) {
            $query->where('type', $request->type);
        }

        // 时间范围过滤
        if ($request->filled('start_date')) {
            $query->whereDate('created_at', '>=', $request->start_date);
        }
        if ($request->filled('end_date')) {
            $query->whereDate('created_at', '<=', $request->end_date);
        }

        $settlements = $query->orderBy('created_at', 'desc')
                           ->paginate($request->get('per_page', 15));

        return response()->json([
            'success' => true,
            'data' => $settlements,
            'summary' => [
                'total_amount' => Settlement::where('tenant_id', Auth::user()->tenant_id)->sum('amount'),
                'pending_amount' => Settlement::where('tenant_id', Auth::user()->tenant_id)
                                             ->where('status', 'pending')->sum('amount'),
                'completed_amount' => Settlement::where('tenant_id', Auth::user()->tenant_id)
                                               ->where('status', 'completed')->sum('amount'),
            ]
        ]);
    }

    /**
     * 获取结算记录详情
     */
    public function show($id)
    {
        $settlement = Settlement::with(['task', 'taskApplication', 'tenant'])
            // ->where('tenant_id', Auth::user()->tenant_id)
            ->where('tenant_id', 1)
            ->findOrFail($id);

        return response()->json([
            'success' => true,
            'data' => $settlement
        ]);
    }

    /**
     * 创建结算记录
     */
    public function store(Request $request)
    {
        $request->validate([
            'task_id' => 'required|exists:tasks,id',
            'task_application_id' => 'required|exists:task_applications,id',
            'type' => ['required', Rule::in(['task_completion', 'bonus', 'penalty', 'refund'])],
            'amount' => 'required|numeric|min:0',
            'description' => 'nullable|string|max:500',
        ]);

        // 验证任务和申请是否属于当前租户
        $task = Task::where('tenant_id', Auth::user()->tenant_id)
                   ->findOrFail($request->task_id);
        
        $taskApplication = TaskApplication::where('tenant_id', Auth::user()->tenant_id)
                                        ->where('task_id', $request->task_id)
                                        ->findOrFail($request->task_application_id);

        DB::beginTransaction();
        try {
            $settlement = Settlement::create([
                'tenant_id' => Auth::user()->tenant_id,
                'task_id' => $request->task_id,
                'task_application_id' => $request->task_application_id,
                'type' => $request->type,
                'amount' => $request->amount,
                'description' => $request->description,
                'status' => 'pending',
                'created_by' => Auth::id(),
            ]);

            DB::commit();

            return response()->json([
                'success' => true,
                'message' => '结算记录创建成功',
                'data' => $settlement->load(['task', 'taskApplication'])
            ], 201);
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json([
                'success' => false,
                'message' => '创建失败：' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * 批准结算
     */
    public function approve($id, Request $request)
    {
        $request->validate([
            'note' => 'nullable|string|max:500',
        ]);

        $settlement = Settlement::where('tenant_id', Auth::user()->tenant_id)
                               ->where('status', 'pending')
                               ->findOrFail($id);

        DB::beginTransaction();
        try {
            // 计算税务信息
            $taxResult = $this->taxService->calculatePersonalTax($settlement->amount, 'freelancer');
            
            if ($taxResult['success']) {
                $settlement->tax_amount = $taxResult['tax_amount'];
                $settlement->calculateNetAmount();
            }

            $settlement->update([
                'status' => 'approved',
                'approved_at' => now(),
                'approved_by' => Auth::id(),
                'approval_note' => $request->note,
            ]);

            // 发送短信通知
            if ($settlement->taskApplication && $settlement->taskApplication->phone) {
                $this->smsService->sendSettlementNotification(
                    $settlement->taskApplication->phone,
                    $settlement->amount,
                    'approved'
                );
            }

            DB::commit();

            Log::info('结算审批成功', [
                'settlement_id' => $settlement->id,
                'approved_by' => Auth::id()
            ]);

            return response()->json([
                'success' => true,
                'message' => '结算已批准',
                'data' => $settlement->fresh(['task', 'taskApplication'])
            ]);
        } catch (\Exception $e) {
            DB::rollBack();
            Log::error('结算审批失败', [
                'settlement_id' => $settlement->id,
                'error' => $e->getMessage()
            ]);
            
            return response()->json([
                'success' => false,
                'message' => '批准失败：' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * 完成结算（发起银行转账）
     */
    public function complete($id, Request $request)
    {
        $request->validate([
            'payment_method' => 'required|string|max:50',
            'bank_account' => 'required|string|max:50',
            'account_name' => 'required|string|max:100',
            'note' => 'nullable|string|max:500',
        ]);

        $settlement = Settlement::where('tenant_id', Auth::user()->tenant_id)
                               ->where('status', 'approved')
                               ->findOrFail($id);

        DB::beginTransaction();
        try {
            // KYC验证银行卡信息
            $kycResult = $this->kycService->verifyBankCard(
                $request->bank_account,
                $request->account_name
            );

            if (!$kycResult['success'] || !$kycResult['verified']) {
                throw new \Exception('银行卡验证失败');
            }

            // 更新结算状态为处理中
            $settlement->update([
                'status' => 'processing',
                'payment_method' => $request->payment_method,
                'completed_by' => Auth::id(),
                'completion_note' => $request->note,
            ]);

            // 发起银行转账
            $transferData = [
                'amount' => $settlement->net_amount,
                'recipient_account' => $request->bank_account,
                'recipient_name' => $request->account_name,
                'reference' => $settlement->settlement_number,
                'description' => $settlement->description ?? '任务结算转账'
            ];

            $transferResult = $this->bankService->initiateTransfer($transferData);

            if ($transferResult['success']) {
                $settlement->update([
                    'status' => 'completed',
                    'completed_at' => now(),
                    'bank_transaction_id' => $transferResult['transaction_id'],
                ]);

                // 发送完成通知短信
                if ($settlement->taskApplication && $settlement->taskApplication->phone) {
                    $this->smsService->sendSettlementNotification(
                        $settlement->taskApplication->phone,
                        $settlement->net_amount,
                        'completed'
                    );
                }

                DB::commit();

                Log::info('结算完成', [
                    'settlement_id' => $settlement->id,
                    'bank_transaction_id' => $transferResult['transaction_id']
                ]);

                return response()->json([
                    'success' => true,
                    'message' => '结算已完成',
                    'data' => $settlement->fresh(['task', 'taskApplication'])
                ]);
            } else {
                throw new \Exception('银行转账失败');
            }
        } catch (\Exception $e) {
            DB::rollBack();
            
            // 更新结算状态为失败
            $settlement->update([
                'status' => 'failed',
                'completion_note' => '转账失败：' . $e->getMessage()
            ]);

            Log::error('结算完成失败', [
                'settlement_id' => $settlement->id,
                'error' => $e->getMessage()
            ]);
            
            return response()->json([
                'success' => false,
                'message' => '完成失败：' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * 查询银行转账状态
     */
    public function checkTransferStatus($id)
    {
        $settlement = Settlement::where('tenant_id', Auth::user()->tenant_id)
                               ->findOrFail($id);

        if (!$settlement->bank_transaction_id) {
            return response()->json([
                'success' => false,
                'message' => '未找到银行交易ID'
            ], 400);
        }

        try {
            $statusResult = $this->bankService->queryTransferStatus($settlement->bank_transaction_id);
            
            if ($statusResult['success']) {
                // 根据银行返回状态更新结算状态
                if ($statusResult['status'] === 'completed' && $settlement->status === 'processing') {
                    $settlement->update([
                        'status' => 'completed',
                        'completed_at' => now()
                    ]);
                } elseif ($statusResult['status'] === 'failed') {
                    $settlement->update([
                        'status' => 'failed',
                        'completion_note' => '银行转账失败'
                    ]);
                }

                return response()->json([
                    'success' => true,
                    'data' => [
                        'settlement' => $settlement->fresh(),
                        'bank_status' => $statusResult
                    ]
                ]);
            } else {
                return response()->json([
                    'success' => false,
                    'message' => '查询转账状态失败'
                ], 500);
            }
        } catch (\Exception $e) {
            Log::error('查询转账状态失败', [
                'settlement_id' => $settlement->id,
                'error' => $e->getMessage()
            ]);
            
            return response()->json([
                'success' => false,
                'message' => '查询失败：' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * 批量转账
     */
    public function batchTransfer(Request $request)
    {
        $request->validate([
            'settlement_ids' => 'required|array|min:1',
            'settlement_ids.*' => 'exists:settlements,id'
        ]);

        $settlements = Settlement::where('tenant_id', Auth::user()->tenant_id)
                                ->where('status', 'approved')
                                ->whereIn('id', $request->settlement_ids)
                                ->with(['taskApplication'])
                                ->get();

        if ($settlements->count() !== count($request->settlement_ids)) {
            return response()->json([
                'success' => false,
                'message' => '部分结算记录不存在或状态不正确'
            ], 400);
        }

        DB::beginTransaction();
        try {
            $transfers = [];
            foreach ($settlements as $settlement) {
                $transfers[] = [
                    'amount' => $settlement->net_amount,
                    'recipient_account' => $settlement->taskApplication->bank_account ?? '',
                    'recipient_name' => $settlement->taskApplication->real_name ?? $settlement->taskApplication->name,
                    'reference' => $settlement->settlement_number,
                    'description' => $settlement->description ?? '任务结算转账'
                ];
            }

            $batchResult = $this->bankService->batchTransfer($transfers);

            if ($batchResult['success']) {
                foreach ($settlements as $index => $settlement) {
                    $transferResult = $batchResult['transfers'][$index];
                    $settlement->update([
                        'status' => 'processing',
                        'bank_transaction_id' => $transferResult['transaction_id'],
                        'completed_by' => Auth::id(),
                        'completion_note' => '批量转账处理中'
                    ]);
                }

                DB::commit();

                return response()->json([
                    'success' => true,
                    'message' => '批量转账已发起',
                    'data' => [
                        'batch_id' => $batchResult['batch_id'],
                        'processed_count' => $settlements->count()
                    ]
                ]);
            } else {
                throw new \Exception('批量转账发起失败');
            }
        } catch (\Exception $e) {
            DB::rollBack();
            
            Log::error('批量转账失败', [
                'settlement_ids' => $request->settlement_ids,
                'error' => $e->getMessage()
            ]);
            
            return response()->json([
                'success' => false,
                'message' => '批量转账失败：' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * 拒绝结算
     */
    public function reject($id, Request $request)
    {
        $request->validate([
            'reason' => 'required|string|max:500',
        ]);

        $settlement = Settlement::where('tenant_id', Auth::user()->tenant_id)
                               ->where('status', 'pending')
                               ->findOrFail($id);

        DB::beginTransaction();
        try {
            $settlement->update([
                'status' => 'rejected',
                'rejected_at' => now(),
                'rejected_by' => Auth::id(),
                'rejection_reason' => $request->reason,
            ]);

            DB::commit();

            return response()->json([
                'success' => true,
                'message' => '结算已拒绝',
                'data' => $settlement->fresh(['task', 'taskApplication'])
            ]);
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json([
                'success' => false,
                'message' => '拒绝失败：' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * 批量操作
     */
    public function batchAction(Request $request)
    {
        $request->validate([
            'action' => ['required', Rule::in(['approve', 'reject', 'complete'])],
            'ids' => 'required|array|min:1',
            'ids.*' => 'required|integer|exists:settlements,id',
            'reason' => 'required_if:action,reject|string|max:500',
            'note' => 'nullable|string|max:500',
            'payment_method' => 'required_if:action,complete|string|max:50',
            'transaction_id' => 'nullable|string|max:100',
        ]);

        $settlements = Settlement::where('tenant_id', Auth::user()->tenant_id)
                                ->whereIn('id', $request->ids)
                                ->get();

        if ($settlements->count() !== count($request->ids)) {
            return response()->json([
                'success' => false,
                'message' => '部分结算记录不存在或无权限操作'
            ], 400);
        }

        DB::beginTransaction();
        try {
            $successCount = 0;
            foreach ($settlements as $settlement) {
                switch ($request->action) {
                    case 'approve':
                        if ($settlement->status === 'pending') {
                            $settlement->update([
                                'status' => 'approved',
                                'approved_at' => now(),
                                'approved_by' => Auth::id(),
                                'approval_note' => $request->note,
                            ]);
                            $successCount++;
                        }
                        break;
                    case 'reject':
                        if ($settlement->status === 'pending') {
                            $settlement->update([
                                'status' => 'rejected',
                                'rejected_at' => now(),
                                'rejected_by' => Auth::id(),
                                'rejection_reason' => $request->reason,
                            ]);
                            $successCount++;
                        }
                        break;
                    case 'complete':
                        if ($settlement->status === 'approved') {
                            $settlement->update([
                                'status' => 'completed',
                                'completed_at' => now(),
                                'completed_by' => Auth::id(),
                                'payment_method' => $request->payment_method,
                                'transaction_id' => $request->transaction_id,
                                'completion_note' => $request->note,
                            ]);
                            $successCount++;
                        }
                        break;
                }
            }

            DB::commit();

            return response()->json([
                'success' => true,
                'message' => "批量操作完成，成功处理 {$successCount} 条记录"
            ]);
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json([
                'success' => false,
                'message' => '批量操作失败：' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * 获取结算统计
     */
    public function statistics(Request $request)
    {
        $tenantId = Auth::user()->tenant_id;
        
        // 基础统计
        $totalAmount = Settlement::where('tenant_id', $tenantId)->sum('amount');
        $pendingAmount = Settlement::where('tenant_id', $tenantId)
                                  ->where('status', 'pending')->sum('amount');
        $approvedAmount = Settlement::where('tenant_id', $tenantId)
                                   ->where('status', 'approved')->sum('amount');
        $completedAmount = Settlement::where('tenant_id', $tenantId)
                                    ->where('status', 'completed')->sum('amount');
        $rejectedAmount = Settlement::where('tenant_id', $tenantId)
                                   ->where('status', 'rejected')->sum('amount');

        // 按类型统计
        $typeStats = Settlement::where('tenant_id', $tenantId)
                              ->selectRaw('type, COUNT(*) as count, SUM(amount) as total_amount')
                              ->groupBy('type')
                              ->get();

        // 月度统计
        $monthlyStats = Settlement::where('tenant_id', $tenantId)
                                 ->selectRaw('DATE_FORMAT(created_at, "%Y-%m") as month, COUNT(*) as count, SUM(amount) as total_amount')
                                 ->groupBy('month')
                                 ->orderBy('month', 'desc')
                                 ->limit(12)
                                 ->get();

        return response()->json([
            'success' => true,
            'data' => [
                'summary' => [
                    'total_amount' => $totalAmount,
                    'pending_amount' => $pendingAmount,
                    'approved_amount' => $approvedAmount,
                    'completed_amount' => $completedAmount,
                    'rejected_amount' => $rejectedAmount,
                ],
                'type_stats' => $typeStats,
                'monthly_stats' => $monthlyStats,
            ]
        ]);
    }
}